package com.alpha.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class CommonUtils {
    public static final ThreadLocal threadLocal = new ThreadLocal();

    public static void removeThreadLocal() {
        threadLocal.remove();
    }

    public static void setLocalData(String key, Object value) {
        Map<String, Object> map = getLocalData();
        map.put(key, value);
        threadLocal.set(map);
    }

    public static Map<String, Object> getLocalData() {
        Map<String, Object> map = (Map<String, Object>) threadLocal.get();
        if (map == null) {
            map = new HashMap<String, Object>();
            threadLocal.set(map);
        }
        return map;
    }

    public static String getLocalData(String key) {
        Map<String, Object> map = (Map<String, Object>) threadLocal.get();
        if (map == null) {
            map = new HashMap<String, Object>();
            map.put(key, "");
            threadLocal.set(map);
        }
        String value = map.get(key).toString();
        return value == null ?  "" : value;
    }


    /**
     * map加入一个map数据
     * @param targetMap 目标数据
     * @param sourceMap 源数据
     * @return map
     */
    public static Map extendMap(Map targetMap, Map sourceMap) {
        for (Object key : sourceMap.keySet()) {
            targetMap.put(key, sourceMap.get(key));
        }
        return targetMap;
    }

    /**
     * json字符串转map
     * @param jsonStr json字符串
     * @return map
     */
    public static Map<String, String> jsonStrToMap(String jsonStr) {
        Map map = new HashMap();
        JSONObject json = JSON.parseObject(jsonStr);
        for (Map.Entry entry : json.entrySet()) {
            if (entry.getValue() != null)
                map.put(entry.getKey(), entry.getValue().toString());
        }
        return map;
    }
}
